﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Frogism.Core;
using Frogism.Data;


namespace Frogism.Domain {
     class BookManager :ManagerBase<Book,IBook>, IBookManager{
      public Collection<int> YearList {
        get {
            IEnumerable<IBook> books = this.GetAll();
          IEnumerable<int> years = from b in books select b.GoalYear;
          return years.Distinct().ToCollection();
        }
      }
      private BookLoader _Loader;
      public override ILoader<Book,IBook> Loader {
        get {
          if(_Loader == null) {
            _Loader = new BookLoader();
          }
          return _Loader;
        }
      }
      public IRead GetReadById(IBook book, int readId)
      {
          return  book.Reads.Single(r => r.Id == readId);
      }
      public IRead GetOrCreateTodaysRead(IBook book)
      {
          IRead read = book.Reads.SingleOrDefault(r => r.ReadDate == DateTime.Now.CleanDate());
          if (read == null)
          {
              read = new Read();
              read.Id = -1;
              read.Page = 0;
              read.ReadDate = DateTime.Now.CleanDate();
          }
          return read;
      }
      public Collection<IBook> GetReading() {
        return this.GetAll().Where(b => !b.IsFinished && b.Reads.Count() > 0).ToCollection<IBook>();
      }
      public void Update(IBook book) {
        BookLoader b = new BookLoader();
        if (book.Id <= 0) {
          b.Create(book);
        } else {
          b.Save(book);
        }
      }
      public void UpdateRead(IBook book,IRead read)
      {
          ReadLoader rl = new ReadLoader();

          if (read.Id <= 0)
          { // New Read
              rl.Create(book.Id,read);
          }
          else
          {
              rl.Save(read);
          }

      }
   
   
      public void DeleteRead(IRead read) {
        ReadLoader rl = new ReadLoader();
        rl.Delete(read.Id);
      }

      public IEnumerable<IBook> GetPublicReading() {
        return GetReading().Where(b => !b.IsPrivate).OrderByDescending(b => b.Reads.Max(r => r.ReadDate));
      }





      public IEnumerable<IBook> GetFinished() {
        throw new NotImplementedException();
      }
     }
}